// 用户认证状态管理
class AuthManager {
  constructor() {
    this.tokenKey = 'accessToken'
    this.userInfoKey = 'userInfo'
    this.userIdKey = 'userId'
    this.usernameKey = 'username'
    this.roleCodesKey = 'roleCodes'
    this.hasTagKey = 'hasTag'
  }

  // 检查是否已登录
  isLoggedIn() {
    const token = this.getToken()
    const userId = this.getUserId()
    const isLoggedIn = !!(token && userId)
    console.log('AuthManager.isLoggedIn - token:', token, 'userId:', userId, 'result:', isLoggedIn)
    return isLoggedIn
  }

  // 获取token
  getToken() {
    return uni.getStorageSync(this.tokenKey)
  }

  // 设置token
  setToken(token) {
    uni.setStorageSync(this.tokenKey, token)
  }

  // 获取用户ID
  getUserId() {
    return uni.getStorageSync(this.userIdKey)
  }

  // 设置用户ID
  setUserId(userId) {
    uni.setStorageSync(this.userIdKey, userId)
  }

  // 获取用户名
  getUsername() {
    return uni.getStorageSync(this.usernameKey)
  }

  // 设置用户名
  setUsername(username) {
    uni.setStorageSync(this.usernameKey, username)
  }

  // 获取角色代码
  getRoleCodes() {
    const roleCodes = uni.getStorageSync(this.roleCodesKey)
    return roleCodes ? JSON.parse(roleCodes) : []
  }

  // 设置角色代码
  setRoleCodes(roleCodes) {
    uni.setStorageSync(this.roleCodesKey, JSON.stringify(roleCodes))
  }

  // 获取是否有标签
  getHasTag() {
    return uni.getStorageSync(this.hasTagKey)
  }

  // 设置是否有标签
  setHasTag(hasTag) {
    uni.setStorageSync(this.hasTagKey, hasTag)
  }

  // 获取用户信息
  getUserInfo() {
    const userInfo = uni.getStorageSync(this.userInfoKey)
    return userInfo ? JSON.parse(userInfo) : null
  }

  // 设置用户信息
  setUserInfo(userInfo) {
    uni.setStorageSync(this.userInfoKey, JSON.stringify(userInfo))
  }

  // 保存登录信息
  saveLoginInfo(loginData) {
    console.log('AuthManager.saveLoginInfo - 输入数据:', loginData)
    
    const { accessToken, userId, username, roleCodes, hasTag, nickname, avatar, email, phone, filePath } = loginData
    
    this.setToken(accessToken)
    this.setUserId(userId)
    this.setUsername(username)
    this.setRoleCodes(roleCodes || [])
    this.setHasTag(hasTag)
    
    // 构建用户信息对象，包含所有可能的字段
    const userInfo = {
      id: userId,
      username: username,
      nickname: nickname || username,
      avatar: avatar || '',
      filePath: filePath || '',
      email: email || '',
      phone: phone || '',
      roleCodes: roleCodes || [],
      hasTag: hasTag
    }
    this.setUserInfo(userInfo)
    
    console.log('AuthManager.saveLoginInfo - 保存的用户信息:', userInfo)
    console.log('AuthManager.saveLoginInfo - 保存完成，token:', this.getToken(), 'userId:', this.getUserId())
  }

  // 清除登录信息
  clearLoginInfo() {
    uni.removeStorageSync(this.tokenKey)
    uni.removeStorageSync(this.userIdKey)
    uni.removeStorageSync(this.usernameKey)
    uni.removeStorageSync(this.roleCodesKey)
    uni.removeStorageSync(this.hasTagKey)
    uni.removeStorageSync(this.userInfoKey)
  }

  // 更新用户信息
  updateUserInfo(updates) {
    const currentUserInfo = this.getUserInfo()
    if (currentUserInfo) {
      const updatedUserInfo = { ...currentUserInfo, ...updates }
      this.setUserInfo(updatedUserInfo)
      
      // 如果更新了用户名，也要更新存储
      if (updates.username) {
        this.setUsername(updates.username)
      }
    }
  }

  // 检查是否有特定角色
  hasRole(roleCode) {
    const roleCodes = this.getRoleCodes()
    return roleCodes.includes(roleCode)
  }

  // 检查是否有管理员权限
  isAdmin() {
    return this.hasRole('admin')
  }

  // 检查是否有商户权限
  isMerchant() {
    return this.hasRole('merchant')
  }

  // 检查是否有学员权限
  isStudent() {
    return this.hasRole('student')
  }

  // 获取用户显示名称
  getDisplayName() {
    const userInfo = this.getUserInfo()
    return userInfo?.nickname || userInfo?.username || '用户'
  }

  // 获取用户头像
  getAvatar() {
    const userInfo = this.getUserInfo()
    return userInfo?.filePath || userInfo?.avatar || ''
  }
}

// 创建单例实例
const authManager = new AuthManager()

export default authManager
